package com.wcity.manage.web.community;

import com.wcity.manage.common.bean.RetBean;
import com.wcity.manage.common.context.Constants;
import com.wcity.manage.common.context.SessionKey;
import com.wcity.manage.common.enums.Code;
import com.wcity.manage.common.enums.SaveImageType;
import com.wcity.manage.common.exception.CustomException;
import com.wcity.manage.common.utils.DwzUtil;
import com.wcity.manage.common.utils.JSONUtil;
import com.wcity.manage.common.utils.RespUtil;
import com.wcity.manage.common.utils.request.RequestUtil;
import com.wcity.manage.common.vo.community.social.SocialInfoVo;
import com.wcity.manage.common.vo.community.workguide.WorkGuideVo;
import com.wcity.manage.dao.dal.model.PageModel;
import com.wcity.manage.dao.model.Block;
import com.wcity.manage.dao.model.User;
import com.wcity.manage.dao.model.community.image.ImageUrl;
import com.wcity.manage.dao.model.community.remark.CommunityRemark;
import com.wcity.manage.dao.model.community.social.SocialInfo;
import com.wcity.manage.service.BlockService;
import com.wcity.manage.service.RegisterService;
import com.wcity.manage.service.community.remark.CommunityRemarkService;
import com.wcity.manage.service.community.social.SocialInfoService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 社工
 * Created by hgg on 2016/12/20.
 */
@Controller
public class SocialInfoAct {

    private final static Logger log = LoggerFactory.getLogger(SocialInfoAct.class);

    @Autowired
    private SocialInfoService socialInfoService;
    @Autowired
    private BlockService blockService;
    @Autowired
    private CommunityRemarkService communityRemarkService;
    @Autowired
    private RegisterService registerService;

    /**
     * 社工列表
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "community_socialInfo_list")
    public String socialInfoList( HttpServletRequest request, PageModel model,HttpServletResponse response ) {

        try {

            //【1】封装参数/参数校验
            Map<String, Object> requestMap = RequestUtil.getGetData(request);

            //【2】获取当前用户信息
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询数据
            requestMap.put( "start", ( model.getPageNum() - 1) * model.getNumPerPage() );
            requestMap.put( "end", model.getNumPerPage());
            requestMap.put( "userId", user.getId() );
            List<SocialInfoVo> socialInfoVos = socialInfoService.socialInfoPageList(requestMap);

            //【4】查询总数量
            Integer totalSocialInfo = socialInfoService.totalSocialInfo(requestMap);
            model.setTotal( totalSocialInfo );

            request.setAttribute( "socialInfos", socialInfoVos );
            request.setAttribute( "pageModel", model );
            request.setAttribute( "nickname", requestMap.get( "nickname" ) );
            request.setAttribute( "blockId", requestMap.get( "blockId" ) );
            request.setAttribute( "status", requestMap.get( "status" ) );

            //【5】查询用户管理的小区列表
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "userId",user.getId() );
            List<Block> blocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blocks",blocks );
        } catch ( Exception e ) {
            log.error( "查询社工列表异常:" + e.getMessage() );
        }
        return "community/socialinfo/list";
    }

    /**
     * 执行删除社工
     *
     * @param request
     */
    @RequestMapping(value = "delete_community_socialInfo")
    @ResponseBody
    public void deleteSocialInfo( HttpServletRequest request, HttpServletResponse response ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "删除成功";
        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if (requestMap.get("id") == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "请选择一条记录", "", "", "", ""));
                return;
            }

            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return;
            }

            requestMap.put( "communityUserId",user.getId() );
            //【3】执行删除
            Integer deleteNum = socialInfoService.deleteSocialInfo( requestMap );
            if ( deleteNum == 0 ) {
                code = Constants.STATUS_ERROR_DWZ;
                message = "删除失败";
            }
        } catch ( Exception e ) {
            log.error( "删除社工异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "删除失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "", "", "", ""));
    }

    /**
     * 新增社工
     *
     * @param socialInfo
     * @param response
     */
    @RequestMapping(value = "save_add_community_socialInfo")
    @ResponseBody
    public void addSocialInfo( SocialInfo socialInfo, HttpServletResponse response, HttpServletRequest request ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "保存成功";

        try {
            //【1】校验参数
            String imgUrl = request.getParameter( "imageUrl" );
            if ( StringUtils.isBlank( socialInfo.getIntention() ) || StringUtils.isBlank( imgUrl ) ) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", "" ) );
                return;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute(SessionKey.SESSION_USER_INFO);
            if ( user == null ) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return;
            }

            //【3】执行保存社工
            socialInfo.setUserId( user.getId() );
            socialInfoService.saveAddSocialInfo(socialInfo,"");

        } catch ( Exception e ) {
            log.error( "保存社工异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "保存失败";
        }
        RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( code, message, "community_socialInfo_list", "", "closeCurrent", "" ) );
    }

    /**
     * 跳转到编辑社工页面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "to_edit_community_socialInfo")
    public String socialInfoDetail( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if ( requestMap.get("id") == null ) {
                return null;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询社工数据
            requestMap.put("userId", user.getId());
            SocialInfoVo socialInfoVo = socialInfoService.socialInfoDetail(requestMap);
            request.setAttribute( "socialInfo", socialInfoVo );
            if (socialInfoVo == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "数据不存在", "", "", "", ""));
                return null;
            }

        } catch ( Exception e ) {
            log.error( "查询社工失败: " + e.getMessage() );
            RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "查询失败", "", "", "", ""));
        }

        return "community/socialinfo/edit";
    }

    /**
     * 更新社工
     *
     * @param socialInfo
     * @param response
     */
    @RequestMapping(value = "save_edit_community_socialInfo")
    @ResponseBody
    public void updateSocialInfo( SocialInfo socialInfo, HttpServletResponse response, HttpServletRequest request ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "更新成功";

        try {

            //【1】校验参数
            if ( socialInfo.getId() == null ) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", "" ) );
                return;
            }

            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if (user == null) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return;
            }

            //【3】执行更新社工
            socialInfo.setCommunityUserId( user.getId() );
            socialInfo.setStatus( 1 );
            socialInfoService.saveUpdateSocialInfo( socialInfo );

        } catch ( Exception e ) {
            log.error( "更新社工异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "更新失败";
        }
        RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( code, message, "community_socialInfo_list", "", "closeCurrent", "" ) );
    }

    /**
     * 跳转到添加社工的页面
     * @return
     */
    @RequestMapping(value = "to_add_community_socialInfo")
    public String toAddSocialInfo( HttpServletRequest request,HttpServletResponse response ){

        try {

            //【1】获取当前用户信息
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【2】查询用户管理的小区列表
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "userId",user.getId() );
            String blocks = socialInfoService.blockIds( queryMap );
            queryMap.put( "notContain",1 );
            queryMap.put( "ids",blocks );
            List<Block> queryBlocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blocks",queryBlocks );

        }catch ( Exception e ){
            log.error( "跳转到志愿者服务页面异常：" + e.getMessage() );
        }
        return "community/socialinfo/add";
    }

    /**
     * 跳转到查看社工详情页面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "to_detail_community_socialInfo")
    public String socialInfoDetailPage( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if ( requestMap.get("id") == null ) {
                return null;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询社工数据
            requestMap.put("userId", user.getId());
            SocialInfoVo socialInfoVo = socialInfoService.socialInfoDetail(requestMap);
            request.setAttribute( "socialInfo", socialInfoVo );
            if ( socialInfoVo == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "数据不存在", "", "", "", ""));
                return null;
            }
            //【4】查看备注列表
            requestMap.clear();
            requestMap.put( "referId",socialInfoVo.getId() );
            requestMap.put( "remarkType","consultation" );
            List<CommunityRemark> remarks = communityRemarkService.remarkList( requestMap );
            request.setAttribute( "remarks",remarks );

        } catch ( Exception e ) {
            log.error( "查询社工失败: " + e.getMessage() );
            RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "查询失败", "", "", "", ""));
        }

        return "community/socialinfo/detail";
    }

    /**
     * 跳转到添加备注页面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "to_add_remark_community_socialInfo")
    public String socialInfoAddRemark( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if ( requestMap.get("id") == null ) {
                return null;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            request.setAttribute( "socialInfoId",requestMap.get("id") );
        } catch ( Exception e ) {
            RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "查询失败", "", "", "", ""));
        }

        return "community/socialinfo/add-remark";
    }

    /**
     * 执行保存备注
     * @return
     */
    @RequestMapping(value = "save_add_remark_community_socialInfo")
    public void saveAddRemark( HttpServletRequest request,HttpServletResponse response,CommunityRemark communityRemark ){

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "添加成功";
        try {

            //【1】校验参数
            if ( StringUtils.isBlank( communityRemark.getRemark() ) ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", ""));
                return;
            }

            //【2】获取用户
            User user = (User) request.getSession().getAttribute(SessionKey.SESSION_USER_INFO);
            if (user == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", ""));
                return;
            }
            //【3】执行保存备注
            communityRemark.setRemarkType( "socialInfo" );
            Integer saveNum = communityRemarkService.saveAddRemark( communityRemark );
            if( saveNum == 0 ){
                code = Constants.STATUS_ERROR_DWZ;
                message = "添加失败";
            }
        }catch ( Exception e ){
            log.error( "添加社工备注失败:" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "添加失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "community_socialInfo_list", "", "closeCurrent", ""));
    }

    /**********************************************************H5端****************************************************************/

    /**
     * 执行保存社工报名（H5端）
     * @param request
     * @return
     */
    @RequestMapping(value = "v1/community_socialInfo_save_h5")
    @ResponseBody
    public Object saveAddSocialInfo( HttpServletRequest request,SocialInfo socialInfo ){

        Integer num = 0;
        try {
            //【1】校验参数
            String registerId = request.getParameter( "registerId" );
            if( StringUtils.isBlank( registerId ) || StringUtils.isBlank( socialInfo.getUserRealName() )
                    || StringUtils.isBlank( socialInfo.getIntention() ) || StringUtils.isBlank( socialInfo.getUserMobile() ) ){
                throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
            }

            //【2】获取当前用户信息
            Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
            if( userMap == null || userMap.get( "blockId" ) == null ){
                throw new CustomException( "用户信息不存在", Code.ERROR );
            }

            //【3】执行保存
            socialInfo.setBlockId( (Integer) userMap.get( "blockId" ) );
            socialInfo.setStatus(0);
            socialInfo.setUserId( Integer.parseInt( registerId ) );
            socialInfo.setCommunityUserId( (Integer) userMap.get( "userId" ) );
            num = socialInfoService.saveAddSocialInfo( socialInfo,null );
        }catch ( Exception e ){
            log.error( "保存失败:" + e.getMessage() );
        }
        if( num == 0 ){
            return new RetBean( Code.ERROR, "保存失败" );
        }else {
            return new RetBean( Code.SUCCESS, "保存成功" );
        }

    }

    /**
     * 社工报名列表列表
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "v1/community_socialInfo_list_h5")
    @ResponseBody
    public Object socialInfoListH5( HttpServletRequest request, PageModel model,HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String,Object> requestMap = new HashedMap();
            String registerId = request.getParameter( "registerId" );
            if( StringUtils.isBlank( registerId ) ){
                throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
            }

            //【2】获取当前用户信息
            Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
            if( userMap == null || userMap.get( "blockId" ) == null ){
                throw new CustomException( "用户信息不存在", Code.ERROR );
            }

            //【2】查询数据
            requestMap.put( "start", ( model.getPageNum() - 1) * model.getNumPerPage() );
            requestMap.put( "end", model.getNumPerPage() );
            requestMap.put( "blockId",userMap.get( "blockId" ) );
            List<SocialInfoVo> socialInfoVos = socialInfoService.socialInfoPageList( requestMap );

            //【3】查询总数量
            Integer totalWorkGuide = socialInfoService.totalSocialInfo( requestMap );
            model.setTotal( totalWorkGuide );

            Map<String,Object> map = JSONUtil.getSuccessJson();
            map.put( "data",socialInfoVos );
            map.put( "pageModel",model );
            return map;
        } catch ( Exception e ) {
            log.error( "查询社工报名列表异常:" + e.getMessage() );
            return null;
        }
    }

    /**
     * 社工信息详情（H5）
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "v1/community_socialInfo_detail_h5")
    @ResponseBody
    public Object workGuideDetailH5( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String,Object> requestMap = new HashedMap();
            String registerId = request.getParameter( "registerId" );
            String id = request.getParameter( "id" );
            if( StringUtils.isBlank( registerId ) || StringUtils.isBlank( id ) ){
                throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
            }

            //【2】获取当前用户信息
            Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
            if( userMap == null || userMap.get( "blockId" ) == null ){
                throw new CustomException( "用户信息不存在", Code.ERROR );
            }

            //【3】查询社工信息详情
            requestMap.put( "id", Integer.parseInt( id ) );
            requestMap.put( "blockId",userMap.get( "blockId" ) );
            SocialInfoVo socialInfoVo = socialInfoService.socialInfoDetail( requestMap );
            if ( socialInfoVo == null ) {
                return null;
            }
            Map<String,Object> map = JSONUtil.getSuccessJson();
            map.put( "data",socialInfoVo );
            return map;
        } catch ( Exception e ) {
            log.error( "查询办事指南失败: " + e.getMessage() );
            return null;
        }

    }

    /**
     * 删除社工信息（H5）
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "v1/community_socialInfo_delete_h5")
    @ResponseBody
    public RetBean workGuideDeleteH5( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String,Object> requestMap = new HashedMap();
            String registerId = request.getParameter( "registerId" );
            String id = request.getParameter( "id" );
            if( StringUtils.isBlank( registerId ) || StringUtils.isBlank( id ) ){
                throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
            }

            //【2】获取当前用户信息
            Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
            if( userMap == null || userMap.get( "blockId" ) == null ){
                throw new CustomException( "用户信息不存在", Code.ERROR );
            }

            //【3】删除社工信息详情
            requestMap.put( "id", Integer.parseInt( id ) );
            requestMap.put( "communityUserId",userMap.get( "userId" ) );
            Integer deleteNum = socialInfoService.deleteSocialInfo( requestMap );
            if ( deleteNum == 0 ) {
                return new RetBean( Code.SUCCESS, "删除失败" );
            }else {
                return new RetBean( Code.SUCCESS, "删除成功" );
            }
        } catch ( Exception e ) {
            log.error( "删除社工报名记录失败: " + e.getMessage() );
            return new RetBean( Code.SUCCESS, "删除失败" );
        }

    }
}
